package dk.oldommer.bjw.model.user;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import dk.oldommer.bjw.HibernateUtil;

public class TestUserFacade {

	private UserFacade userFacade = new UserFacadeImpl();
	private UserValues userValuesA;
	private UserValues userValuesB;
	
	@Before
	public void setup() {
		userValuesA = new User();
		userValuesA.setUserName("UserName-A");
		userValuesA.setFirstName("FirstName-A");
		
		userValuesB = new User();
		userValuesB.setUserName("UserName-B");
		userValuesB.setFirstName("FirstName-B");
	}
	
	@After
	public void teardown() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.createQuery("delete from User").executeUpdate();
		session.getTransaction().commit();
	}
	
	@Test
	public void testCreate() {
		try {
			User user = userFacade.create(userValuesA);
			assertNotNull(user);
			assertNotNull(user.getId());
		}
		
		catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@Test
	public void testFindAll() {
		try {
			userFacade.create(userValuesA);
			userFacade.create(userValuesB);
			int elementsInserted = userFacade.findAll().size();
			assertTrue("findAll() should return the inserted users, not " + elementsInserted, (elementsInserted == 2));
		} catch (FacadeException e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@Test
	public void testGet() {
		try {
			Long id = userFacade.create(userValuesA).getId();
			assertEquals(
					"get(id) doesn't return the expected User", 
					userValuesA.getUserName(), 
					userFacade.get(id).getUserName());
		} catch (FacadeException e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@Test
	public void testSave() {
		try {
			User user = userFacade.create(userValuesA);
			user.setCity("MyCity");
			userFacade.save(user.getId(), user);
			user = userFacade.get(user.getId());
			assertEquals("Update failed", "MyCity", user.getCity());
		} catch (FacadeException e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

}
